package com.vertxExample.starter;

import com.fasterxml.jackson.core.JsonPointer;
import com.fasterxml.jackson.core.JsonpCharacterEscapes;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.templ.thymeleaf.ThymeleafTemplateEngine;
import io.vertx.ext.web.templ.thymeleaf.impl.ThymeleafTemplateEngineImpl;

public class TemplateVerticle extends AbstractVerticle {
	// create object router
	Router router;
	// 1. 声明模板引擎
	ThymeleafTemplateEngine thymeleafTemplateEngine;

	@Override
	public void start(Promise<Void> startPromise) throws Exception {
		Router router = Router.router(vertx);

		// 2. 初始化模板引擎
		thymeleafTemplateEngine = ThymeleafTemplateEngine.create(vertx);

		// 4. 配置router解析url
		router.route("/").handler(req -> {
			JsonObject jsonObject = new JsonObject();
			jsonObject.put("name","hello world from back engine");
			//3. render
			thymeleafTemplateEngine.render(jsonObject, "templates/index.html",
				bufferAsyncResult -> {
				if (bufferAsyncResult.succeeded()) {
					req.response()
						.putHeader("content-type", "text/html")
						.end(bufferAsyncResult.result());
				} else {
					req.response().end("error");
				}
			});

		});

		// config url
		vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
			if (http.succeeded()) {
				startPromise.complete();
				System.out.println("HTTP server started on port 8888");
			} else {
				startPromise.fail(http.cause());
			}
		});
	}
}
